package com.gxhmplan.util;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

public class Util {
	/**
	 * 加盐
	 * @param data 密码
	 * @param salt 盐值
	 * @return 加盐后的密码
	 */
	public static String saltMd5(String data,String salt) {
		return DigestUtils.md5Hex(data + salt);
	}
	/**
	 * 获得验证码
	 */
	public static void getValidate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获得 当前请求 对应的 会话对象
		HttpSession session = request.getSession();

		final int width = 100; // 图片宽度
		final int height = 40; // 图片高度
		final String imgType = "jpeg"; // 指定图片格式 (不是指MIME类型)
		final OutputStream output = response.getOutputStream(); // 获得可以向客户端返回图片的输出流
		// (字节流)
		// 创建验证码图片并返回图片上的字符串
		String code = GraphicHelper.create(width, height, imgType, output);
		System.out.println("验证码内容: " + code);
		System.out.println(Util.object2String(request.getParameter("msg")));
		// 建立 uri 和 相应的 验证码 的关联 ( 存储到当前会话对象的属性中 )
		session.setAttribute(Util.object2String(request.getParameter("msg")), code);
	}

	/**
	 * 检验验证码是否正确
	 */
	public static boolean checkValidate(HttpServletRequest request, String validate) {
		HttpSession session = request.getSession();
		// 获得生成的验证码
		String msg = Util.object2String(request.getParameter("msg"));
		String validate1 = object2String(session.getAttribute(msg)).toLowerCase();
		if (validate1.equals(validate.toLowerCase())) {
			request.removeAttribute(msg);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Object转换成String，如果为空则返回空字符串
	 */
	public static String object2String(Object o) {
		return o == null ? "" : o + "";
	}
	
	/**
	 * 发送短信验证码
	 * @param phone
	 * @return
	 */
	/*public static SmsSingleSenderResult smsSend(HttpServletRequest request, String phone) {
		try {
			int appid = 1400048702;
			String appkey = "5ef86c44dfbe518ed4618a595b71be0c";
			SmsSingleSender singleSender = new SmsSingleSender(appid, appkey);
			SmsSingleSenderResult singleSenderResult;
			// 普通单发
			int smsValidate = (int)((Math.random()*9+1)*100000);
			HttpSession session = request.getSession();
			session.setAttribute(phone, smsValidate);
			singleSenderResult = singleSender.send(0, "86", phone, "您的验证码是："+smsValidate+"，如非本人操作，请忽略本短信。", "", "");
			return singleSenderResult;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}*/
	
	/**
	 * 检验短信验证码是否正确
	 */
	public static boolean checkSmsValidate(HttpServletRequest request, String validate) {
		HttpSession session = request.getSession();
		// 获得生成的验证码
		String validate1 = object2String(session.getAttribute(Util.object2String(request.getParameter("sms")))).toLowerCase();
		System.out.println("checkSmsValidate:"+validate+","+validate1);
		boolean isTrue = validate1.equals(validate.toLowerCase());
		if (isTrue) {
			session.removeAttribute(Util.object2String(request.getParameter("sms")));
		}
		return isTrue;
	}
	
	/**
	 * 用于跳转到微信登录二维码页面
	 * @return 页面地址
	 */
	public static String toWechatLogin() {
		String appid = "wx1568d1d604301861";
		String redirectUri = "http%3A%2F%2Fwww.dy92.com";
		String state = object2String(UUID.randomUUID());
		String url = "https://open.weixin.qq.com/connect/qrconnect?appid="+appid+
					 "&redirect_uri="+redirectUri+"&response_type=code&scope=snsapi_login&state="+state+"#wechat_redirect";
		return url;
	}
	
	/**
	 * 上传文件
	 * @param file 文件
	 * @param folderName 所存文件夹名
	 * @param request
	 * @return 文件的路径
	 */
	@SuppressWarnings("finally")
	public static String upload(MultipartFile file,String id,String folderName,HttpServletRequest request) {
		/**
		 * 服务器 测试
		 */
		File dir = null;
		String url = null;
		try {
			String fileName = file.getOriginalFilename();
			List<String> list = new ArrayList<String>();
			list.add(".jpeg");
			list.add(".jpg");
			list.add(".png");
			String format = fileName.substring(fileName.lastIndexOf("."));
			if (!list.contains(format)) {
				throw new NameException("上传文件格式错误");
			}
			// 上传的文件命名:id+类型+时间.jpg
			fileName = id + "_" + folderName + "_" + Util.object2String(new Date().getTime()) + format;
			String path = request.getSession().getServletContext().getRealPath("upload/") + folderName;//tomcat容器下
//			String request_path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
//			String path = request_path + "/upload/" + folderName;
			url = "/upload/" + folderName +"/"+ fileName;
			System.out.println(path);
			dir = new File(path, fileName);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// MultipartFile自带的解析方法
			file.transferTo(dir);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			return url;
		}
		
		/**
		 * 本地测试  
		 */
		/*File dir = null;    
		try {
	        	String fileName = file.getOriginalFilename();
	        	List<String> list = new ArrayList<String>();
	        	list.add(".jpeg");
	        	list.add(".jpg");
	        	list.add(".png");
	        	String format = fileName.substring(fileName.lastIndexOf("."));
	        	System.out.println(format);
	        	if (!list.contains(format)) {
	        		throw new NameException("上传文件格式错误");
	        	}
	        	System.out.println(fileName);
	        	//上传的文件命名:id+类型+时间.jpg
	        	fileName = id+"_"+folderName+"_"+Util.object2String(new Date().getTime())+format;
	        	String path = "f:/"+folderName+"/";
		        dir = new File(path,fileName); 
		        System.out.println(path);
		        System.out.println(dir);
		        if(!dir.exists()){
		            dir.mkdirs();  
		        }  
		        //MultipartFile自带的解析方法 
				file.transferTo(dir);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				return "http://localhost:9992/"+folderName+"/"+dir.getName();
			}*/
	}
	public static void deletePortrait(String photoName,HttpServletRequest request) {
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String reqGetPhone(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		// 从Cookie中获取phone
		String phone = null;
		if (cookies != null) {
			for (Cookie c : cookies) {
				if ("phone".equals(c.getName())) {
					phone = c.getValue();
				}
			}
		}
		return phone;
	}
	public static String reqGetId(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		// 从Cookie中获取phone
		String id = null;
		if (cookies != null) {
			for (Cookie c : cookies) {
				if ("id".equals(c.getName())) {
					id = c.getValue();
				}
			}
		}
		return id;
	}
	//通过xml 发给微信消息  
    public static String wxXml(String return_code, String return_msg) {  
        return "<xml><return_code><![CDATA[" + return_code + "]]>" +   
                "</return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";  
    }
    /** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public static String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
    public static String delHTMLTag(String htmlStr) {
    	String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
    	Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //过滤html标签
        return htmlStr.trim(); //返回文本字符串
    }
}